package chapter06;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class MyAtomicInteger {
    protected volatile int value;
    private static long valueoffset;
    private static Unsafe UNSAFE;
    static {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            UNSAFE= (Unsafe) theUnsafe.get(null);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        try {
            valueoffset=UNSAFE.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public int getValue(){
        return this.value;
    }

    public void decrement(int amount){
        while (true){
            int pre=getValue();
            int next=pre-amount;
            if (UNSAFE.compareAndSwapInt(this,valueoffset,pre,next)){
                break;
            }
        }
    }

}
